<?php

namespace App\Common\Lib\Hyperf\QueryExtend\Cache;

use App\Common as com;
use App\Common\Lib\Hyperf\QueryExtend\Cache\Driver as nameDriver;

class Driver extends com\Lib\LibBase {

	/**
	 * @TODO :: 暂时不支持
	 * 方案参考：https://github.com/renoki-co/laravel-eloquent-query-cache/blob/ddc276a0de6706b0610c7530278a652abac4961b/README.md
	 * @param $tags
	 * @return $this
	 */
	public function tags( $tags ) {
		return $this;
	}

	/**
	 * @param $key
	 * @param int|null $expire 有效时间，单位：秒。[null]永久 [int]必须大于0
	 * @param $fn
	 * @return \Hyperf\Utils\Collection
	 */
	public function remember( $key, $expire, $fn ) {
		$cacheKeyDb = com\Lib\Cache\KeyDB::use( $key );
		$value = $cacheKeyDb->getOrSet( function () use ( $fn ) {
			[
				$fnRes,
				$fnValue
			] = $this->callFn( $fn );
			return $fnValue;
		}, $expire );
		return new \Hyperf\Utils\Collection( $value );
	}

	public function rememberForever( $key, $fn ) {
		$cacheKeyDb = com\Lib\Cache\KeyDB::use( $key );
		$value = $cacheKeyDb->getOrSet( function () use ( $fn ) {
			[
				$fnRes,
				$fnValue
			] = $this->callFn( $fn );
			return $fnValue;
		}, null );
		return new \Hyperf\Utils\Collection( $value );
	}

	private function callFn( $fn ) {
		$fnRes = $fn();
		if( $fnRes instanceof \Hyperf\Utils\Collection ){
			$fnValue = $fnRes->toArray();
		} else{
			$fnValue = $fnRes;
		}
		//
		return [
			$fnRes,
			$fnValue
		];
	}
}
